#!/usr/bin/python3
# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*-

import os
import sys
import shutil
import argparse
sys.path.append('/usr/lib64/wrtd')
from wrt_util import WrtUtil
from wrt_param import WrtConst
from wrt_param import WrtParam
from wrt_daemon import WrtDaemon

# parse parameter
parseResult = None
if True:
    argParser = argparse.ArgumentParser()
    argParser.add_argument("--abort-on-error", dest="abort_on_error", action="store_true", help="Abort initialization when error")
    argParser.add_argument("-d", "--debug-level", dest='debug_level',
                           choices=['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG'], default="INFO",
                           help="Set output debug message level")
    parseResult = argParser.parse_args()

param = WrtParam()

try:
    # fill WrtParam according to argument
    if param.abortOnError is not None:
        param.abortOnError = parseResult.abort_on_error
    param.logLevel = parseResult.debug_level

    # create logDir
    WrtUtil.ensureDir(WrtConst.logDir)

    # create tmpDir
    WrtUtil.mkDirAndClear(WrtConst.tmpDir)

    # start server
    WrtDaemon(param).run()
finally:
    if os.path.exists(param.tmpDir):
        shutil.rmtree(param.tmpDir)
    if os.path.exists(param.runDir):
        shutil.rmtree(param.runDir)
